package com.fengmi.user.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.fengmi.exception.JWTParseException;
import com.fengmi.jwt.JwtUtils;
import com.fengmi.jwt.RsaUtils;
import com.fengmi.user.SysUser;
import com.fengmi.user.mapper.SysUserMapper;
import com.fengmi.user.service.ISysUserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fengmi.vo.ResultVO;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.util.ResourceUtils;

import java.io.FileNotFoundException;
import java.security.PrivateKey;
import java.security.PublicKey;

/**
 * <p>
 * 用户信息表 服务实现类
 * </p>
 *
 * @author zhuxm
 * @since 2021-10-22
 */
@Service
public class SysUserServiceImpl extends ServiceImpl<SysUserMapper, SysUser> implements ISysUserService {

    @Override
    public ResultVO login(SysUser user) {
        if(user ==null){
            return new ResultVO(false,"用户名密码必须填写");
        }
        //获取用户信息
        QueryWrapper<SysUser> queryWrapper=new QueryWrapper<>();
        queryWrapper.eq("account",user.getAccount());
        queryWrapper.eq("user_type","6");
        SysUser sysUser = this.baseMapper.selectOne(queryWrapper);
        if (sysUser ==null){
            return new ResultVO(false,"用户名或密码错误");
        }
        //比较密码

        BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
        if (!encoder.matches(user.getPassword(),sysUser.getPassword())){
            return new ResultVO(false,"用户名或密码错误");
        }
        //颁发jwt令牌
        //加载私钥
        try {
            String path = ResourceUtils.getFile("classpath:rsa_pri").getPath();
            PrivateKey privateKey = RsaUtils.getPrivateKey(path);
            sysUser.setPassword("");
            String token = JwtUtils.generateTokenExpireInMinutes(sysUser, privateKey, 40);
            return new ResultVO(true,"success",token);
        } catch (Exception e) {
            e.printStackTrace();
            return new ResultVO(false,"用户名或密码错误");
        }
    }

    @Override
    public ResultVO login(String phone, String code) {
        return null;
    }

    @Override
    public ResultVO verifyToken(String token) {
        try {
            PublicKey publicKey = null;
            try {
                publicKey = RsaUtils.getPublicKey(ResourceUtils.getFile("classpath:rsa_pub").getPath());
            } catch (Exception e) {
                e.printStackTrace();
            }
            Object UserInfo = JwtUtils.getInfoFromToken(token, publicKey, SysUser.class);
            return new ResultVO(true,"合法令牌");
        } catch (JWTParseException e) {
            e.printStackTrace();
            return  new ResultVO(false,"无效令牌");
        }
    }
}
